﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Misc.xaml.cs" company="None">
//   <Author>Adrian von Allmen, 2013</Author>
// </copyright>
// <summary>
//   Filter Miscellaneous UserControl
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Filter_Misc
{
    using System.Collections.Specialized;
    using System.ComponentModel.Composition;
    using System.Data;
    using System.IO;
    using System.Linq;

    using CrumbleLibrary;

    using Filter_Misc.Properties;

    /// <summary>
    /// Filter Miscellaneous UserControl
    /// </summary>
    [Export("ReportFilter", typeof(IFilterPlugins))]
    [ExportMetadata("Id", "MiscFilterID")]
    [ExportMetadata("Filtername", "Various")]
    public partial class FilterMisc
    {
        /// <summary>
        /// The display name of Filter Form.
        /// </summary>
        public const string DisplayName = "Misc";

        /// <summary>
        /// The data set table name.
        /// </summary>
        private const string DataSetTableName = "Repository";

        /// <summary>
        /// Repository for manage values and save them
        /// </summary>
        private readonly DataSet valueRepository = new DataSet("ValueRepository_TabMisc");

        /// <summary>
        /// Initializes a new instance of the <see cref="FilterMisc"/> class.
        /// </summary>
        public FilterMisc()
        {
            InitializeComponent();
            this.InitDataSet();

            this.DynamicFilterArea.ItemsSource = this.DynamicFilterItemsCollection;
            this.DynamicFilterItemsCollection.CollectionChanged += this.DynamicFilterItemsCollectionOnCollectionChanged;
        }

        /// <summary>
        /// Save all Setting as serialized DataSet
        /// </summary>
        public override void Save()
        {
            foreach (var item in this.DynamicFilterItemsCollection)
            {
                this.AddRow(item);
            }

            Settings.Default.ValueRepository = this.valueRepository.GetXml();
            Settings.Default.Save();
        }

        /// <summary>
        /// The initialize data set.
        /// </summary>
        private void InitDataSet()
        {
            var validationValue = new StringReader(Settings.Default.ValueRepository);
            var readLine = validationValue.ReadLine();
            if (!string.IsNullOrEmpty(readLine))
            {
                this.valueRepository.ReadXml(new StringReader(Settings.Default.ValueRepository));
            }
            else
            {
                var dataTable = new DataTable(DataSetTableName);
                dataTable.Columns.Add("Tag", typeof(string));
                dataTable.Columns.Add("Value", typeof(object));
                this.valueRepository.Tables.Add(dataTable);
            }
        }

        /// <summary>
        /// The dynamic filter items collection on collection changed.
        /// </summary>
        /// <param name="sender"> The sender. </param>
        /// <param name="notifyCollectionChangedEventArgs"> The notify collection changed event args. </param>
        private void DynamicFilterItemsCollectionOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
        {
            this.HandleValues();
        }

        /// <summary>
        /// Add the Dynamic Filter in Table
        /// </summary>
        /// <param name="item">
        /// The item.
        /// </param>
        private void AddRow(FilterItemDynamic item)
        {
            var selectStatement = string.Format("Tag='{0}'", item.Name);
            var selectRow = this.valueRepository.Tables[DataSetTableName].Select(selectStatement).FirstOrDefault();
            if (selectRow == null)
            {
                var dr = this.valueRepository.Tables[DataSetTableName].NewRow();
                dr[0] = item.Name;
                dr[1] = item.Value;
                this.valueRepository.Tables[DataSetTableName].Rows.Add(dr);
            }
            else
            {
                selectRow.BeginEdit();
                selectRow["Value"] = item.Value;
                selectRow.EndEdit();
            }
        }

        /// <summary>
        /// Pass the Values to the "Save-Setting"-DataSet
        /// </summary>
        private void HandleValues()
        {
            foreach (var item in this.DynamicFilterItemsCollection)
            {
                var selectStatement = string.Format("Tag='{0}'", item.Name);
                var selectRow = this.valueRepository.Tables[DataSetTableName].Select(selectStatement).FirstOrDefault();
                if (selectRow == null)
                {
                    this.AddRow(item);
                }
                else
                {
                    item.Value = selectRow["Value"];
                }
            }
        }
    }
}
